<?php

namespace App\Admin\Controllers;

use App\Http\Models\Topic;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * Class TopicController
 * @package App\Admin\Controllers
 *
 * @note php artisan make:controller App\\Admin\\Controllers\\TopicController -m Http\\Models\\Topic
 */
class TopicController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $topics = Topic::all();

        return view('admin.topic.index', compact('topics'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.topic.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     */
    public function store(Request $request)
    {
        // 校验
        $rules = [
            'name' => 'required|string|min:2',
        ];
        $this->validate($request, $rules);

        // 保存
        Topic::query()->create($request->only('name'));

        // 渲染
        return redirect('/admin/topics');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Http\Models\Topic  $topic
     */
    public function destroy(Topic $topic)
    {
        if (!$topic->exists()) {
            return  ['code' => -1, 'msg' => '该专题已经删除'];
        }
        $topic->delete();

        return ['code' => 0, 'msg' => 'success'];
    }
}
